import { Token_Key } from '@/config'
import { useAppSelector } from '@/store/hooks'
import { useLocation, Navigate } from 'react-router-dom'
export const deepFilterChild = (treeData: IRoutesType[], pathname: string): IRoutesType[] => {
  return treeData?.reduce((acc: IRoutesType[], item) => {
    if (item.fullPath === pathname) {
      acc.push(item)
    }
    if (item.children && item.children.length > 0) {
      const filteredChildren = deepFilterChild(item.children, pathname)
      if (filteredChildren.length > 0) {
        const itemWithFilteredChildren = { ...item, children: filteredChildren }
        acc.push(itemWithFilteredChildren)
      }
    }
    return acc
  }, [])
}

export default function routerBefore({ children }: any) {
  const userRouteList = useAppSelector((state) => state.login.userRouteList)
  const token = window.localStorage.getItem(Token_Key)
  const location = useLocation()
  const result = deepFilterChild(userRouteList, location.pathname)
  if (!token) {
    return (
      <Navigate
        to={'/login' + '?' + encodeURIComponent((location?.pathname || '') + (location?.search || ''))}
        replace
      ></Navigate>
    )
  } else if (location.pathname === '/') {
    if (userRouteList && userRouteList.length > 0) {
      if (userRouteList[0].children && userRouteList[0].children.length > 0) {
        return <Navigate to={userRouteList[0].children[0]?.fullPath || '/login'} replace></Navigate>
      } else {
        return <Navigate to={userRouteList[0]?.fullPath || '/login'} replace></Navigate>
      }
    } else {
      return <Navigate to="/login" replace></Navigate>
    }
  } else if (result && result.length > 0) {
    return <>{children}</>
  } else {
    return <Navigate to="/403" replace></Navigate>
  }
}
